#include "thread.h"
#include "current_thread.h"

#include <atomic>
#include <cstdio>
#include <memory>
#include <semaphore.h>
#include <thread>

std::atomic_int Thread::num_created_(0);

Thread::Thread(ThreadFunc func, const std::string &name)
    : started_(false), joined_(false), tid_(0), func_(std::move(func)), name_(name) {}

Thread::~Thread() {
    if (started_ && !joined_) {
        thread_->detach(); // thread类提供的设置分离线程的方法，防止孤儿线程
    }
}

void Thread::start() { // 一个thread对象，记录的是一个线程的详细信息
    started_ = true;
    sem_t sem;
    sem_init(&sem, false, 0);

    // 开启线程
    thread_ = std::shared_ptr<std::thread>(new std::thread([&]() {
        // 获取tid值
        tid_ = current_thread::tid();
        sem_post(&sem);
        // 开启一个新线程，专门执行该线程函数
        func_();
    }));

    // 这里必需等待上面新创建的tid值,这里为了一个一个对齐，所以使用信号量同步
    sem_wait(&sem);
}

void Thread::join() {
    joined_ = true;
    thread_->join();
}

void Thread::set_default_name() {
    int num = ++num_created_;
    if (name_.empty()) {
        char buf[32] = {0};
        snprintf(buf, sizeof buf, "Thread%d", num);
        name_ = buf;
    }
}